﻿using System;
using System.Linq;
using DNT.RavenQA.Core.Models;
using Raven.Abstractions.Indexing;
using Raven.Client.Indexes;

namespace DNT.RavenQA.Web.Infrastructure.Indexing
{
    public class QuestionsTagListIndex : AbstractIndexCreationTask<Question, QuestionsTagListIndex.ReduceResult>
    {
        public const String INDEX_NAME = "QuestionsTagList";

		public class ReduceResult
		{
            public String Name { get; protected set; }
            public Int32 Count { get; protected set; }
		}

        public override String IndexName
        {
            get { return INDEX_NAME; }
        }

        public QuestionsTagListIndex()
        {
            Map = questions => questions.SelectMany(question => question.Tags,
                                                    (question, tag) => new
                                                                           {
                                                                               Name = tag.ToLower(),
                                                                               Count = 1
                                                                           });
            Reduce = results => results.GroupBy(tagCount => tagCount.Name)
                                       .Select(g => new
                                                        {
                                                            Name = g.Key,
                                                            Count = g.Sum(x => x.Count)
                                                        });

            Indexes.Add(x => x.Name, FieldIndexing.Analyzed);
            Analyzers.Add(x => x.Name, "WhitespaceAnalyzer");
        }
    }
}